package persistence

import (
	"context"
	"encoding/json"

	"github.com/samber/do/v2"
	"gorm.io/gorm"

	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/domain/entity"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/domain/repository"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/infrastructure/persistence/model"
)

type SkuPersistence struct {
	db *gorm.DB
}

func NewSkuRepository(i do.Injector) (repository.SkuRepository, error) {
	db := do.MustInvoke[*gorm.DB](i)
	return &SkuPersistence{
		db: db,
	}, nil
}

func (s SkuPersistence) BatchSave(ctx context.Context, tx *gorm.DB, skus []*entity.Sku) error {
	var skuList = make([]model.ProductSku, len(skus), len(skus))
	for idx, sku := range skus {
		attributes, _ := json.Marshal(sku.Attributes)

		skuList[idx] = model.ProductSku{
			ID:          sku.ID,
			ProductID:   sku.ProductID,
			SkuSn:       sku.SkuSN,
			Attributes:  string(attributes),
			ShopPrice:   sku.ShopPrice,
			MarketPrice: sku.MarketPrice,
			Status:      0,
		}
	}
	tx = tx.WithContext(ctx).CreateInBatches(skuList, len(skuList))
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}
